package spring.lottery.controller.handle;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import spring.lottery.common.exception.ServerException;
import spring.lottery.common.pojo.ResponseMode;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(ServerException.class)
    public ResponseMode handleServerException(ServerException e) {
        log.error("Sever发送了错误， 错误码： {} 信息: {}", e.getCode(), e.getMessage(), e);
        return ResponseMode.fail("发生了错误"+e.getMessage());
    }


    //从方法外和参数上抛出的valid异常是区别的
    @ExceptionHandler({
            MethodArgumentNotValidException.class,  // 处理@RequestBody验证
            HandlerMethodValidationException.class // 处理@RequestParam/@PathVariable验证
    })
    public ResponseMode validException(Exception e) {
        log.error("参数校验失败 ：{}",e.getMessage(),e);
        return ResponseMode.fail("发生了错误"+e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public ResponseMode handleException(Exception e) {
        log.error("请求发生了未知的错误 信息: {}", e.getMessage(), e);
        return ResponseMode.fail("发生了错误"+e.getMessage());
    }

}
